%% Parameters
tic
clc
clear all

ticker = 'MSN';

from_time = 2008;   % select whole time period for in sample
to_time = 2012;

y_in = 7;      % in sample period (quarters)
y_out = 1;     % out sample period (quarters)

% FOR FA
time_lag = 2;             % delay time for FA data
% time_lag = 1;

tool_FA = 'NN';           % select the model to predict FA return:
hiddenLayerSize_FA = 20;  % neural network or stepwise
% tool_FA = 'step';     

normalize_type = 'quar';  % normalize data FA in each quater/ratio
% normalize_type = 'ratio';

% FOR TA
gap_TA = 10;              % time to change the pattern
window = 37;              % time to finish patterns
gap_ret = 5;              % return 'gap_ret' days (1-4: 5 gap_ret)

tool_TA = 'NN';           % select the model to predict TA return:
hiddenLayerSize_TA = 20;  % neural network or stepwise
% tool_TA = 'step';
                          
% P&L
trade_type = 'normal';          % normal: using close prices
% trade_type = 'worst';         % worst: BUY - using high; SELL - using low

tran_cost = 0.003;

%% Prepare all variables

[stock_id, all_ret_predicted, all_ret_real, all_prices_clo,...
    all_prices_hi, all_prices_lo, all_dates_ret, data_FA] = ...
    ...
    prepare_variables(ticker, from_time, to_time, normalize_type,...
    y_in, y_out, time_lag, gap_ret, tool_FA, hiddenLayerSize_FA, ...
    gap_TA, window, tool_TA, hiddenLayerSize_TA);

%% Trading strategy and compute P&L, cummulative P&L

trades = trading_strategy(all_ret_predicted);

[all_p_l , all_dates_b, all_dates_s] = compute_PL...
    (trades, all_prices_clo, all_prices_hi, all_prices_lo,...
    all_dates_ret, trade_type, tran_cost);

cumu_p_l = [0; 100*(cumprod(1 + all_p_l) - 1)];
%% Plot the predicted return & real return

all_dates_ret_num = datenum(all_dates_ret, 'yyyy-mm-dd');
all_dates_num = [];

idx = 1:1:size(all_ret_predicted,1)-1;
for i = 1:size(all_ret_predicted,1)
    ret_dates = all_dates_ret_num(2*i-1);
    all_dates_num = [all_dates_num ; ret_dates];
end

figure('name','Returns comparision')
hold on
plot(all_dates_num, all_ret_predicted,'--b', 'linewidth', 3);
plot(all_dates_num, all_ret_real,'--r', 'linewidth', 3);
ax = axis;
axis([all_dates_num(1,1) all_dates_num(end,1) ax(3:4)]);
add_dates('format', 'dd/mm/yyyy', 'font_size', 12);
hold off

title('Comparision btw predicted & real return', 'fontsize', 12);
legend('predicted return', 'real return');
ylabel('Return (%)','fontsize',12);
%% Plot the trading strategy & backtest

[stock_prices, stock_prices_ret_b, stock_prices_ret_s,...
    stock_dates_b, stock_dates_s, all_dates_ret_num,...
    all_ret_predicted_dup, all_ret_real_dup, all_dates_ret_num_b,...
    all_dates_ret_num_s, idx_buy, idx_sell, all_dates_p_l_num] =...
    ...
    prepare_plot(all_dates_b, all_dates_s, all_dates_ret_num,...
    stock_id, all_dates_ret, all_ret_predicted, all_ret_real,...
    trades, cumu_p_l);

figure('name','Trading strategy');

h1 = subplot(3,1,1);
hold on
plot(stock_prices(:,1), stock_prices(:,6),'k','linewidth',2.5);
plot(stock_dates_b, stock_prices_ret_b,'bo', 'linewidth', 2, 'MarkerSize',10);
plot(stock_dates_s,stock_prices_ret_s, 'ro', 'linewidth', 2, 'MarkerSize',10);
ax = axis;
axis([stock_prices(1,1) stock_prices(end,1) ax(3:4)]);
add_dates('format', 'dd/mm/yyyy', 'font_size', 12);
hold off

title('Trading strategy and P&L', 'fontsize', 12);
legend('stock prices', 'BUY', 'SELL');
ylabel('Prices','fontsize',12);

h2 = subplot(3,1,2);
hold on
stairs(all_dates_ret_num, all_ret_predicted_dup,'--r','linewidth',2.5);
stairs(all_dates_ret_num, all_ret_real_dup,'--b','linewidth',2.5);
plot(all_dates_ret_num_b(idx_buy), all_ret_real(idx_buy),'bo', 'linewidth', 2, 'MarkerSize',10);
plot(all_dates_ret_num_s(idx_sell),all_ret_real(idx_sell), 'ro', 'linewidth', 2, 'MarkerSize',10);
ax = axis;
axis([all_dates_ret_num(1) all_dates_ret_num(end) ax(3:4)]);
add_dates('format', 'dd/mm/yyyy', 'font_size', 12);
hold off

legend('predicted return', 'real return');
ylabel('Return (%)','fontsize',12);

h3 = subplot(3,1,3);
hold on
stairs(all_dates_p_l_num, cumu_p_l,'--b','linewidth',2.5);
ax = axis;
axis([stock_prices(1,1) stock_prices(end,1) ax(3:4)]);
add_dates('format', 'dd/mm/yyyy', 'font_size', 12);
hold off

legend('P&L');
ylabel('P&L (%)','fontsize',12);

linkaxes([h1 h2 h3], 'x');

%% Performance
clc

win = length(find(all_p_l > 0));
lose = length(find(all_p_l < 0));
ave_p_l = mean(all_p_l)*100;
vol_p_l = std(all_p_l)*100;
min_p_l = min(all_p_l)*100;
max_p_l = max(all_p_l)*100;

[f1,x1] = ksdensity(all_p_l, 'kernel', 'epanechnikov'); 
x = [0,0];
y = [0,max(f1)];

figure('name', 'Distribution P&L')
hold on
plot(x1, f1, 'b-', 'linewidth', 2.5);
plot(x,y,'r-', 'linewidth', 2.5);
hold off
title('Distribution of Profit & Loss', 'fontsize', 12);
legend('pdf of P&L');

fprintf('The average and volatility of P&L are %2.3f%% and %2.3f%%\n', ...
    ave_p_l, vol_p_l)
fprintf('The min and max of P&L are %2.3f%% and %2.3f%%\n', ...
    min_p_l,max_p_l)
fprintf('The cummulative P&L is % 2.3f%%\n', cumu_p_l(end))
fprintf('The winning trades/total trades is %d/%d\n', win, length(all_p_l))
fprintf('The lossing trades/total trades is %d/%d\n', lose, length(all_p_l))
toc